package com.example;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import org.slf4j.Logger;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class myAdvice {
    private Logger logger= (Logger) LoggerFactory.getLogger(myAdvice.class);
//   定义切面
    @Pointcut(value = "execution(* com.example.cotroller.*.*(..))")
    public  void myPointCut()
    {
      System.out.println("这里是切点===============");
    }
  //定义环绕通知
    @Around("myPointCut()")
    public Object myLogger1(ProceedingJoinPoint pjp) throws Throwable {
        String className=pjp.getTarget().getClass().toString();
        logger.info(" className=====" +className);
        String methodName=pjp.getSignature().getName();
        Object[] array=pjp.getArgs();
        System.out.println("方法名: " + methodName);
        System.out.println("调用前" +className +"传递的参数为:" + new ObjectMapper().writeValueAsString(array));
       // logger.info("调用前" +className +"传递的参数为:" + new ObjectMapper().writeValueAsString(array));
        Object obj = pjp.proceed();//让方法去执行
        System.out.println("调用后" +className +"返回值 :" + new ObjectMapper().writeValueAsString(obj));
      //  logger.info("调用后" +className +"返回值 :" + new ObjectMapper().writeValueAsString(obj));


        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();

        String uri = request.getRequestURI();
        System.out.println("切面获取 request:" +uri);

        return obj;
    }
}
